import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, Row, Col, message } from 'antd';
import { MailOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
import './RegisterPage.css';

const RegisterPage = () => {
  const [form] = Form.useForm();
  const [captchaUrl, setCaptchaUrl] = useState('/api/captcha');
  const history = useNavigate();

  const handleCaptchaClick = () => {
    setCaptchaUrl(`/api/captcha?_=${Date.now()}`);
  };

  const handleSubmit = async values => {
    console.log('注册信息:', values);
    values = {
      username: values.username,
      password: values.password,
      email: values.email,
    };
    try {
      const response = await fetch(
        'http://localhost:29157/api/users/register',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(values),
        }
      );
      const data = await response.json();

      if (data.status) {
        message.success('注册成功');
        sessionStorage.setItem('token', data.data.access_token); // Store the token in sessionStorage
        history('/');
      } else {
        message.error(`注册失败: ${data.error.message}`);
      }
    } catch (error) {
      message.error(`注册失败: ${error.message}`);
    }
  };

  const handleConfirmPassword = (rule, value, callback) => {
    if (value !== form.getFieldValue('password')) {
      callback('确认密码不一致');
    } else {
      callback();
    }
  };

  const handleEmailValidation = (rule, value, callback) => {
    const emailRegex = /^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i;
    if (!emailRegex.test(value)) {
      callback('请输入正确的邮箱地址');
    } else {
      callback();
    }
  };

  return (
    <div className='register-page'>
      <div className='register-card'>
        <div className='register-card-header'>
          <h2>注册</h2>
        </div>
        <div className='register-card-body'>
          <Form
            form={form}
            onFinish={handleSubmit}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}>
            <Form.Item
              label='昵称'
              name='username'
              rules={[{ required: true, message: '请输入昵称' }]}>
              <Input
                prefix={<UserOutlined />}
                placeholder='请输入昵称'
              />
            </Form.Item>
            <Form.Item
              label='密码'
              name='password'
              rules={[{ required: true, message: '请输入密码' }]}>
              <Input.Password
                prefix={<LockOutlined />}
                placeholder='请输入密码'
              />
            </Form.Item>
            <Form.Item
              label='确认密码'
              name='confirmPassword'
              rules={[
                { required: true, message: '请确认密码' },
                { validator: handleConfirmPassword },
              ]}>
              <Input.Password
                prefix={<LockOutlined />}
                placeholder='请确认密码'
              />
            </Form.Item>
            <Form.Item
              label='邮箱'
              name='email'
              rules={[
                { required: true, message: '请输入邮箱地址' },
                { validator: handleEmailValidation },
              ]}>
              <Input
                prefix={<MailOutlined />}
                placeholder='请输入邮箱地址'
              />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
              <Button
                type='primary'
                htmlType='submit'>
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>

      <div className='register-footer'>
        <p>神奇笔记本 - 一个个人管理系统</p>
        <p>前端：React + Ant Design</p>
        <p>后端：SSM + Spring Boot + Flask</p>
      </div>
    </div>
  );
};

export default RegisterPage;
